#!/bin/bash

PKG_VER=0.0.0
PKG_SVN=0
PKG_PLAT=unknown
SVN_REVISION=unknown


usage() {
    echo "usage: $0 -v version -p platform [-r revision]"
    echo "        version: must be [x.x.x] format, e.g. 1.12.26"
    echo "        platform: must be one of [android, ios]"
    echo "        revision: svn revision number"
}

###################### MAIN #######################

while getopts "v:p:h:r" option; do
    case "$option" in
        v)
            PKG_VER=$OPTARG
            ;;
        p)
            PKG_PLAT=$OPTARG
            ;;
        r)
            SVN_REVISION=$OPTARG
            ;;
        h)
            usage;
            exit 0;
            ;;
        :|\?)
            usage;
            exit 1;
            ;;
    esac
done

if [ "x$PKG_VER" = "x0.0.0" ] || [ "x$PKG_PLAT" = "xunknown" ]; then
    usage;
    exit 1;
fi

basedir=`pwd`
srcdir=$basedir/src
builddir=$srcdir/build
pubdir=$basedir/tkpub
mkdir -p $pubdir

echo "update code begin..."
cd $basedir
if [ "$SVN_REVISION" = "unknown" ]; then
    svn up
else
    svn up -r $SVN_REVISION
fi
echo "svn revision:"$SVN_REVISION
echo "update code end!"

echo "compile code begin..."
rm -rf $builddir
mkdir -p $builddir
cd $builddir
cmake -Drelease=1 $srcdir
make -j4
if [ $? -ne 0 ]; then
    echo "compile code failed!"
    exit 1
fi
cd $basedir
echo "compile code end!"

BRANCH_NAME=`svn info | grep 'Relative URL' | cut -d'/' -f2`
echo "branch name is: $BRANCH_NAME"

PKG_SVN=`svn info | grep Revision | awk '{print $2}'`
echo $PKG_SVN > tkdist/version.txt

[[ -f $basedir/md5.txt ]] && rm -f $basedir/md5.txt

echo "generate md5 sum begin..."
cd $basedir
for f in `find tkdist -type f | grep -v '.svn'`; do
    md5sum $f >> md5.txt
done
echo "generate md5 sum end!"

echo "generate package begin..."
cd $basedir
pkgname=$pubdir/tank_server_${PKG_PLAT}_${BRANCH_NAME}_${PKG_VER}_`date +%Y%m%d%H%M%S`_SVN${PKG_SVN}.tgz
echo "package: $pkgname"
tar czf $pkgname --exclude=*.svn tkdist md5.txt
rm -f md5.txt
echo "generate tkdist package end!"

echo "upload package begin..."
cd $basedir
expect -c '
    set timeout -1
    spawn scp '"$pkgname"' ubuntu@120.92.16.147:/home/ubuntu/upload/
    expect {
        "yes/no" {
            send "yes\r"; exp_continue
        }
        "assword:" {
            send "Thinky789456\r"
        }
    }
    expect eof
    sleep 1
    exit
'
echo "upload package end!"
